import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { MessageBox } from 'element-ui'
import { Message } from 'element-ui'

const service = axios.create({
    withCredentials: true,
    timeout: 5000
});

service.interceptors.request.use(
    config => {
        if (store.state.token && store.state.token !== '') {
            config.headers['token'] = store.state.token
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    res => {
        let url = res.config.url;
        if (res.data.code === 401) {
            // 如果请求的不是登出接口
            if(url.indexOf('logout') == -1) {
                MessageBox.confirm('您还未登录!', '提示', {
                    confirmButtonText: '登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    router.push('/login')
                }).catch(() => {
                    Message.info('取消操作')
                })
            }else {
                // 不做拦截
            }
        }
        return res.data;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

export default service;
